<template>
	<view class="tea-home-app">
		<view class="search" @click="searchPosition">
			<image src="../../../static/search-icon.png" class="image"></image>
			<view class="text" style="font-size:32upx;">
			{{keyword}}
			</view>
		</view>
		<map style="width: 100%; height: 100%;" :show-location="true" :latitude="map.latitude" :longitude="map.longitude" :markers="map.covers" @markertap="markertap" ref="teaHouseMap" id="teaHouseMap">
		</map>
		<view class="actions">

			<view class="customer-action action" @click="goUserHome">
				<image src="../../../static/user_0.png" style="width:60upx;height:60upx;"></image>
			</view>

			<view class="position-action action" @click="initMap">
				<image src="../../../static/map_point.png" style="width:60upx;height:60upx;"></image>
			</view>

			<!--
			优惠券
			-->
			<view class="coupon-action action" style="background-color: #1D2C6D;" @click="goPage('/pages/tea/voucher/index')">
				<image src="../../../static/coupon_v2.png" style="width:40upx;height:40upx;"></image>
				<view class="text" style="color:white;margin-top:5upx;font-weight: bold;font-size: 24upx;">卡券</view>
			</view>

			<!--
			<view class="order-action action" style="background-color: #1D2C6D;" @click="goPage('/pages/user/order/list')">
				<image src="../../../static/home-order.png" style="width:40upx;height:40upx;"></image>
				<view class="text" style="color:white;margin-top:5upx;font-weight: bold;font-size: 24upx;">订单</view>
			</view>
			-->

			<view class="order-action action" style="background-color: #1D2C6D;" @click="goPage('/pages/user/order/list')">
				<image src="../../../static/home-order.png" style="width:40upx;height:40upx;"></image>
				<view class="text" style="color:white;margin-top:5upx;font-weight: bold;font-size: 24upx;">订单</view>
			</view>

			<view class="renewal-order-action action" @click="openHouse">
				<image src="../../../static/store_home.png" style="width:50upx;height:50upx;"></image>
				<view class="text" style="margin-top:5upx;font-weight: bold;font-size: 24upx;color:#999">开门</view>
			</view>

		</view>
		<view class="button" style="border-radius: 50upx;left:200upx;position: fixed;bottom:30upx;margin-top:5upx;background-color:#1D2C6D;color:white;font-size:40upx;padding:30upx 60upx;display: flex;">
			<image src="../../../static/tea.png" style="width:50upx;height:50upx;"></image>
			<text style="margin-left:20upx;" @click="goPage('/pages/tea/v2/houseList')">立即预约</text>
		</view>
		<modal :show="openHouseDialog.show"  @close="openHouseDialog.show=false" @cancel="openHouseDialog.show=false" :show-footer="false" :show-confirm="false" :show-cancel="false" confirm-text="确定" cancel-text="关闭">
      <view v-for="order in orderList" style="border-bottom: 1px solid lightgrey">
        <div class="open-control-item">
          <view style="text-align: center;font-weight: bold;padding: 10px;font-size: 20px;display: inline-flex;">{{order.roomName}}：</view>
          <Button class="open-control open-control-door" @click="openHouseDoor(order.orderNO)">开大门</Button>
          <Button class="open-control open-control-room"  @click="openRoomDoor(order.orderNO)">开包厢</Button>
        </div>
      </view>

		</modal>

    <view v-if="isShowNewUserAd">
      <view style="position: fixed;top: 0;left: 0;z-index: 1000;width: 100%;">
        <image style="width: 100%;height: 100%;"
               src='../../../static/new_user_ad.png'></image>
        <Button class="ad-revice-button" style="background: none;color: #fff;letter-spacing: 18rpx;" @click="getCoupons">立即领取</Button>
      </view>
      <view class="mask-view"></view>
    </view>
	</view>
</template>

<script>
	import wPicker from "@/components/w-picker/w-picker.vue"
	import util from '@/libs/util.js'
	import globalConfig from '../../../config'
	import Modal from '@/components/neil-modal/neil-modal.vue';
	import myTimer from '@/components/my-timer.vue';

	const baseHttp = globalConfig.API_HOST

	export default {
    data() {
      return {
        isShowNewUserAd: false,
				isLogin: false,
				showMap: false,
				isTimerStart: false,
				tabItemValue: 0,
				baseHttp: baseHttp,
				isCancelSubmit: false,
				keyword: '搜索位置找附近茶室',
        orderList: [],
				openHouseDialog: {
					show: false,
				},
				user: {
					userId:null,
					teaHouseName: null
				},
				qrcodeDailog:{
					show: false
				},
				qrcodeRoomDailog: {
					show: false
				},
				tabItems: [
					{value: 0, label: '地图'},
					{value: 1, label: '列表'}
				],
				distanceArr: [
				],
				qcCodeRoom: '',
				order:{
					"orderNO":"",
					"orderType":0,
					"payState":0,
					"predictMoney":8000,
					"remark":"租用包厢",
					"rentMins":4,
					"roomId":9,
					"startTime":"2021-01-01 16:05:38",
					"teaHouseId":8,
					"userId":6,
					"qcCode":"",
					"qcCodeRoom":""
				},
				appMap: null,
				firstMap: {
					latitude: null,
					longitude: null
				},
				map: {
					latitude: '',
					longitude: '',
					covers: [
						/*
						{
							id: 1,
						    latitude: 23.02882,
						    longitude: 113.14278,
							title: '地点1',
							width:50,
							height:50,
						    iconPath: '../../../static/point.png'
						},{
							id: 2,
						    latitude: 23.05980,
						    longitude: 113.16039,
							title: '地点2',
							width:50,
							height:50,
						    iconPath: '../../../static/point.png'
						}*/
					]
				},
				isRent: false,
				listData: {
					items: [
					]
				},
				searchOption: {
					keyword: ''
				}
				/*
				isLogin: false,
				tabItemValue: 0,
				teaListDialog: {
					show: false
				},
				searchOption: {
					keyword: ''
				},
				addDialog: {
					show: false
				},
				currentTeaHouse: {
					id: '',
					name: ''
				},
				teaHouse: {
					items: []
				},
				listData: {
					items: [
						{name: '包厢管理',icon:'../../../static/room.png', 'link': '/pages/tea/room/list'},
						{name: '用户管理',icon:'../../../static/user_manager.png', 'link': '/pages/tea/user/list'},
						{name: '配置管理',icon:'../../../static/config.png', 'link': '/pages/tea/default/config'},
						{name: '设备管理',icon:'../../../static/machine.png', 'link': '/pages/tea/machine/list'},
						{name: '任务管理',icon:'../../../static/task.png', 'link': '/pages/tea/task/list'},
						{name: '用户余额日志',icon:'../../../static/money.png', 'link': '/pages/tea/useMoneyLog/list'},
						{name: '邀请管理',icon:'../../../static/invite.png', 'link': '/pages/tea/invite/list'}
					]
				}
				*/
	        }
	    },
		onLoad(params) {

		},
		onReady() {
			//this.getDataList();
			this.appMap = uni.createMapContext("teaHouseMap",this);
			this.initMap();

			setInterval(()=>{
				this.firstMap.latitude = null;
				console.log("clear");
			},60000);
		},
		onShow() {
			if (global.isLogin()) {
				this.isLogin = true
			} else {
				this.isLogin = false
			}

			this.getUserDetail();

			if (this.isLogin) {

				/*
				appMap.getCenterLocation({
				   success(res) {
					   console.log(JSON.stringify(res))
				   }
				});
				*/
				//appMap.showUserLocation(true);

				//this.getUserDetail();
				/*
				this.checkIsRent();
				setInterval(() => {
					this.checkIsRent();
				},60000);
				*/

				/*
				setInterval(() => {
					if (this.isRent) {
						this.getQRImage();
					}
				},300000);
				*/

			}
		},
		components: {
			Modal,
			myTimer
		},
		computed: {
			/*
			dateRangeValue() {
				return [this.homeData.startDate, this.homeData.endDate]
			}
			*/
		},
	    methods: {
			...util,
			goUserHome() {
				this.goPage('/pages/user/info/home');
			},
			openHouseDoor(orderNo) {
				this.$api.post('/roomOrder/controlMachine', {
					machineType: 3,
					state: 1,
          orderNo: orderNo,
				}).then((response) => {
					if (response.ret===1) {
						this.$Message.success("操作成功")
					} else {
						this.$Message.error(response.msg)
					}
				});
			},
			openRoomDoor(orderNo) {
				this.$api.post('/roomOrder/controlMachine', {
					machineType: 0,
          orderNo: orderNo,
					state: 1
				}).then((response) => {
					if (response.ret===1) {
						this.$Message.success("操作成功")
					} else {
						this.$Message.error(response.msg)
					}
				});
			},
			openHouse(){
				if (this.isLogin) {
					this.$api.post('/roomOrder/getRenting', {

					}).then((response) => {
						if (response.ret===1 && response.data && response.data.length > 0) {
              this.orderList = response.data;
							this.openHouseDialog.show = true;
						} else {
							//this.$Message.error(response.msg)
							this.$Message.error("无订单或订单未开始")
						}
					});

					/*
					this.$api.post('/roomOrder/controlMachine', {
						machineType: 3,
						state: 1
					}).then((response) => {
						if (response.ret===1) {
							this.$Message.success("操作成功")
						} else {
							this.$Message.error(response.msg)
						}
					});
					*/
				} else {
					this.goPage('/pages/user/auth/auth')
					return false;
				}
			},
			initMap() {
				console.log("map init");

				if (this.firstMap.latitude) {
					this.appMap.moveToLocation({
						longitude: this.firstMap.longitude,
						latitude: this.firstMap.latitude
					});
					this.getMapTeaHouse(this.firstMap.longitude, this.firstMap.latitude);
				} else {
					uni.getLocation({
					    type: 'gcj02',
					    success:  (res) => {
							this.map.latitude = res.latitude
							this.map.longitude = res.longitude

							this.firstMap.latitude = res.latitude
							this.firstMap.longitude = res.longitude

							//保存到token
							uni.setStorageSync('firstMap_latitude',res.latitude);
							uni.setStorageSync('firstMap_longitude',res.longitude);

							/*
							this.appMap.moveToLocation({
								longitude: res.longitude,
								latitude: res.latitude
							});
							*/

							this.getMapTeaHouse(res.longitude,res.latitude);
					    },
						fail: (res) => {
							console.log(res);
						}
					});
				}

			},
			searchPosition() {
				uni.chooseLocation({
					success: (res) => {
						this.map.covers = [];
						this.keyword = res.name;

						this.map.latitude = res.latitude
						this.map.longitude = res.longitude

						this.appMap.moveToLocation({
							longitude: res.longitude,
							latitude: res.latitude
						});

						this.getMapTeaHouse(res.longitude, res.latitude);
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					}
				});
			},
			getUserDetail() {

				this.$api.post('/user/getInfo', {

				}).then((response) => {
					if (response.ret === 1) {
						this.user = response.data;
						this.searchOption.keyword = this.user.teaHouseName;
						//this.searchByName({target:{value:this.user.teaHouseName}});
						this.isLogin = true;
					} else {
						this.isLogin = false;
						//this.$Message.info(response.msg)
					}
				})

			},
			showMapInfo(item) {
				//console.log(item);
				//console.log(item);
				if (this.isLogin) {
					this.goPage("/pages/tea/default/mapDetail?id="+item.teaHouseId)
				}

				return false;
			},
			onMapTap(tapPosition) {
				//console.log(tapPosition);
				//tapPosition.detail.latitude
				this.map.covers = [];
				this.getMapTeaHouse(tapPosition.detail.longitude,tapPosition.detail.latitude);
			},
			showQrcodeDialog(field) {
				this[field].show = true;
				this.getQRImage();
			},
			getMapTeaHouse(lon,lat) {
				this.$api.post('/teaHouse/getNear',
					{
						lon:lon,
						lat:lat,
						radius:50000000
					}
				).then((response) => {
					//this.map.covers = [];
					let minDistance = 0;
					this.map.covers = [];
					if (response.data) {
						this.distanceArr = [];

						for(let i = 0; i < response.data.length;i++) {
							let distance = this.getDistance(lat,lon, response.data[i].lat,response.data[i].lon);
							console.log(distance);
							this.distanceArr.push(distance);

							this.map.covers.push({
								id: response.data[i].teaHouseId,
							    latitude: response.data[i].lat,
							    longitude: response.data[i].lon,
								title: response.data[i].name,
								width:30,
								height:30,
							    iconPath: '../../../static/tea_map.png'
							});
						}
						minDistance = Math.min(...this.distanceArr);
						console.log("min distance:" + minDistance);

						//console.log(this.map.covers);
					}

					let mapLabel = "距离最近茶室"+minDistance+"km";
					let mapLabelLength = mapLabel.length;

					/*
					this.map.covers.push({
						id: -1,
					    latitude: lat,
					    longitude: lon,
						title: '我的位置',
						width:50,
						height:50,
					    iconPath: '../../../static/my_point.png'
					});
					*/
				   this.map.covers.push({
						id: -1,
						latitude: lat,
						longitude: lon,
						title: "",
						label: {
							content:mapLabel,
							/*textAlign: "center",*/
							anchorX:-(5*mapLabelLength),
							anchorY:-60,
							padding:5,
							bgColor: "#ffffff",
							borderRadius: 5
						},
						width:30,
						height:30,
						iconPath: '../../../static/point.png'
				   });
				});
			},
			markertap(event) {
				if (event.detail.markerId>1) {
					this.goPage('/pages/tea/v2/houseDetail?teaHouseId='+event.detail.markerId)
				}
			},
			tabClick(item) {
				this.tabItemValue = item.value
				this.showMap = !this.showMap
			},
			searchByName(event) {
				let name = event.target.value;
				if (name && name.length > 0) {

					for(let i = 0; i < this.listData.items.length; i++) {
						//console.log(this.listData.items[i]);
						let index = this.listData.items[i].name.indexOf(name);
						if (index!=-1) {
							this.listData.items[i].show = true;
						} else {
							this.listData.items[i].show = false;
						}
					}
				} else {
					this.setField(this.listData.items, 'show', true);
				}
			},
			cancelOrder() {
				if (this.isCancelSubmit) {
					return false;
				}
				uni.showModal({
				    title: '提示',
				    content: '确定结束？',
				    success:  (res) => {
				        if (res.confirm) {

							//提交请求中
							uni.showLoading({
								title: '提交请求中'
							});

							this._cancelOrder();

				        } else if (res.cancel) {
				            //console.log('用户点击取消');
				        }
				    }
				});

			},
			_cancelOrder() {

				this.isCancelSubmit = true;

				this.$api.post('/roomOrder/finishOrder',
					{
					}
				).then((response) => {
					if (response.ret===1) {
						this.$Message.success("结束订单成功");
						this.checkIsRent();
						this.isCancelSubmit = false;
					} else {
						if (response.msg=="余额不足") {
							//this.$Message.error("what");
							//调用充值接口

							//判断是否会员
							if (response.data===null || response.data===undefined) {
								this.isCancelSubmit = false;
								this.$Message.error(response.msg);
								this.goPage("/pages/user/info/vip");
							} else {
								this.toPay(response.data);
							}

						} else {
							this.$Message.error(response.msg);
							this.isCancelSubmit = false;
						}

					}

				});
			},
			toPay(money) {
				wx.login({
					success: (res) => {
						if (res.code) {
							this.wxCode = res.code;

							this.$api.post('/weixin/recharge',
							  {
								code: this.wxCode,
								money: money
							  }
							).then((response) => {
							  if (response.ret===1) {
								//console.log(response);
								let json = "{"+response.data+"}";
								json = json.replace(/'/g,'"');
								json = JSON.parse(json);

								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: json.timeStamp,
									nonceStr: json.nonceStr,
									package: json.package,
									signType: json.signType,
									paySign: json.paySign,
									success:  (res) => {
										//this._cancelOrder();
										this.$Message.success("支付成功");
										/*
										uni.navigateBack({
											delta: 1
										});
										*/
									},
									fail: function (err) {
										console.log('fail:' + JSON.stringify(err));
									}
								});

							  } else {
								this.$Message.error(response.msg)
							  }
							  this.isCancelSubmit = false;
							});
						}
					}
				});

			},
			getOrderInfo() {
				//判断当前是否有使用中的订单

			},
			getQRImage() {

				this.$api.post('/roomOrder/getQRImage',
					{
						lockType: 0
					}
				).then((imageResponse) => {
					this.order.qcCode = imageResponse.data;
				});

				this.$api.post('/roomOrder/getQRImage',
					{
						lockType: 1
					}
				).then((imageResponse) => {
					this.$nextTick(() => {
						this.order.qcCodeRoom = imageResponse.data;
					})

					//console.log("what");
					//console.log(this.order.qcCodeRoom)
				});


			},
			checkIsRent() {

				this.$api.post("/roomOrder/getRenting",
					{

					}
				).then((response) => {

					if (response.ret===1) {

						this.order = response.data;

						let startTime = new Date(this.order.startTime.replace(/-/g,'/')).getTime()/1000;
						//var endTime = new Date(this.selectedTime.replace(/-/g,'/')).getTime()/1000;
						let currentTime = Date.parse(new Date())/1000;
						let useTime = currentTime - startTime;

						this.order.useTime = "00:00:00";

						if (this.isRent==false) {
							this.getQRImage();
						}
						this.isRent = true;

						this.$nextTick(() => {
							this.$refs.myTimer.setCurrentTime(useTime);
							if (this.isTimerStart==false) {
								this.isTimerStart = true;
								this.$refs.myTimer.start();
							}
						})

					} else {
						this.isRent = false;
					}
				});
			},
			getDataList() {
				uni.showLoading({
					title: '加载中'
				});
				this.$api.post('/teaHouse/queryPage',
					{
						pageNo: 1
					}
				).then((response) => {
					response.data.items = this.setField(response.data, 'show', true);

					this.listData.items = response.data

					if (this.user.teaHouseName) {
						//this.searchByName({target:{value:this.user.teaHouseName}});
					}

					/*
					for(let i = 0; i < this.listData.items.length; i++) {
						//console.log(this.listData.items[i]);
						this.listData.items[i]['typeLabel'] = this.getLabelFromOptions(this.formSearchOptions.typeList, this.listData.items[i]['type']);
					}
					*/

					uni.hideLoading()
				});
			},
			goPage(url) {
				if (!this.isLogin) {
					uni.navigateTo({url: '/pages/user/auth/auth'})
				} else {
					//console.log(url);
					uni.navigateTo({url: url})
				}

			},
	    }
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}

	.tea-home-app{
		background-color: #F5F4F8;
		color:#707070;
		height: 100%;

		.open-control-item{
      text-align: center;
      padding-bottom: 10upx;
		}
		.open-control{
			border: 1upx solid #eee;

		}

		.open-control-door{
			border: 1upx solid #eee;
      display: inline-flex;
      margin: 5upx 10upx;
      line-height: 36px;
      background: #3385FF;
      color: #FFFFFF;
    }

		.open-control-room{
			border: 1upx solid #eee;
      display: inline-flex;
      margin: 5upx 10upx;
      line-height: 36px;
      background: #3385FF;
      color: #FFFFFF;
		}

		.search{
			width:100%;
			padding:20upx;
			background-color: white;
			display: flex;
			.image{
				width:55upx;
				height:40upx;
				margin-right:10upx;
			}
		}
		.actions{
			position: relative;
			.action{
				position: fixed;
				width:100upx;
				height:100upx;
				background-color: white;
				border-radius: 70%;
				z-index: 10;
				font-size:28upx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
			.customer-action{
				left:20upx;
				bottom: 320upx;
			}
			.position-action{

				left:20upx;
				bottom: 180upx;
			   /*
			   right:20upx;
			   bottom: 180upx;
			   */
			}
			.order-action{
				right:20upx;
				bottom: 320upx;
			}
			.renewal-order-action{
				right:20upx;
				bottom: 180upx;
			}
			.coupon-action{
				right:20upx;
				bottom: 460upx;
			}
		}

		.head{
			padding:20upx;
			background-color: white;
		}
		.tip-items{
			.tip-item{
				margin:20upx;
				.tip-item-head{
					font-weight: bold;
					font-size:40upx;
					text-align:center;
					border-bottom: 1upx solid #eee;
					margin-bottom: 10upx;
					padding-bottom: 10upx;
				}
				.tip-item-content{

				}
			}
		}
		.qrcode-is-load{
			font-size:24upx;
			width:400upx;
			height:400upx;
			background-color: #ccc;
			text-align: center;
			line-height: 400upx;
		}

		.tabs{
			border-right:none;
			margin-top:-1upx;
			border-radius: 5upx;
			width:100%;
			background-color: #3385FF;
			color:white;
			font-size:28upx;
			.tab-item{
				text-align: center;
				width:50%;
				padding: 20upx;
				/*border-right:1upx solid #1296db;*/
			}
			.selected{
				background-color: #3385FF;
				font-weight: bold;
				/*border-bottom: 3upx solid blue;*/
			}
		}


		.page-section,.page-body,.tea-manager-app{
			height: 100%;
		}
		.dialog-head{
			text-align: center;
			padding: 10upx;
			border-bottom: 1upx solid #eee;
		}
		.login-button{
			font-size:30upx;
			margin:0 auto;
			background-color:#3385FF;
			color:white;
			width:646upx;
			height:100upx;
			text-align: center;
			line-height: 100upx;
		}
		.search-part{
			position: fixed;
			/*top:0;*/
			width:100%;
			padding-top:20upx;
			background-color: #F5F4F8;
			.search-option-input{
				.keyword-input{

				}
			}

			.search-option{
				background-color: white;
				margin:0 20upx;
				color:#BBBBBB;
				display: flex;
				/*justify-content: center;*/
				align-items: center;
			}
			.tabs{
				border:1px solid #108EE9;
				border-right:none;
				margin:0 20upx;
				border-radius: 5upx;
				width:calc(100% - 40upx);
				background-color: white;
				.tab-item{
					text-align: center;
					width:33%;
					padding: 8upx;
					color:#108EE9;
					border-right:1upx solid #108EE9;
				}
				.selected{
					background-color: #108EE9;
					color:white;

				}
			}
		}

		.order-info{
			background-color: white;
			padding-bottom:100upx;
			.head{
				border-bottom:1upx solid #eee;
				text-align: center;
				font-weight: bold;
			}
			.fields{

			}
			.field{
				padding: 10upx;
				display: flex;
				.title{
					width:250upx;
				}
				.value{

				}
			}
			.cancel-button{
				font-size:40upx;
				margin:0 auto;
				color:white;
				width:750upx;

				height:120upx;
				text-align: center;
				line-height: 120upx;
				margin-top:100upx;
				background-color:#D81E06;
				position: fixed;
				bottom:0;
			}
		}


		.tea-list{
			.tea-item{
				background-color: white;
				/*padding: 20upx;*/
				margin-bottom:20upx;
				display: flex;
				flex-direction: column;
				position: relative;
				.image{

				}
				.map-point{
					width:120upx;
					height:120upx;
					/*background-color: white;*/
					margin-right:20upx;
				}
				.tea-house-info{
					width:100%;
					height:120upx;
					margin-top:-160upx;
					/*
					background-color: black;
					opacity: 0.5;
					*/
					background-color: rgba(0,0,0,0.5);
					padding:20upx;
					color:white;
					font-size:32upx;
					display: flex;
					.base-info{
						flex:1;
					}
					.title{
						font-weight: bold;
					}
					.address{

					}
				}
				.map-item-info{
					display: flex;
					flex-direction: column;
					.map-info{
						text-align: center;
						font-size:24upx;
						/*margin:0 auto;*/
						background-color:#3385FF;
						color:white;

						height:45upx;
						text-align: center;
						line-height: 45upx;
					}
				}
				.content{
					flex: 1;
					.title{
						color:#3385FF;
						font-size:32upx;
					}
				}
			}
		}


		.content-items{
			display: flex;
			flex-wrap: wrap;
			margin-top:20upx;

			.content-item{
				font-size:28upx;
				color:#707070;
				width: 200upx;
				height:200upx;

				margin-right:20upx;
				margin-left:20upx;
				margin-bottom:20upx;
				border: 1upx solid #eee;
				background-color: white;
				justify-content: center;
				align-items: center;
				text-align: center;
			}
		}

	}

</style>
